{{define "content"}}
<div x-data="roleCreate()" x-init="setTimeout(() => init(), 0)">
    <!-- 页面标题 -->
    <div class="mb-6">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-2xl font-bold text-gray-900">创建角色</h1>
                <p class="text-gray-600">创建新的系统角色并分配权限</p>
            </div>
            <div>
                <a href="/system/roles" class="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 flex items-center">
                    <i class="fas fa-arrow-left mr-2"></i>
                    返回角色列表
                </a>
            </div>
        </div>
    </div>

    <!-- 创建表单 -->
    <div class="bg-white rounded-lg shadow-sm p-6">
        <form @submit.prevent="submitForm()">
            <div class="space-y-6">
                <!-- 基本信息 -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- 角色名称 -->
                    <div>
                        <label for="name" class="block text-sm font-medium text-gray-700 mb-2">
                            角色名称 <span class="text-red-500">*</span>
                        </label>
                        <input type="text" 
                               id="name" 
                               x-model="formData.name" 
                               @input="validateName()" 
                               placeholder="请输入角色名称（英文，如：admin）" 
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                               :class="errors.name ? 'border-red-500' : ''">
                        <p x-show="errors.name" class="mt-1 text-sm text-red-600" x-text="errors.name"></p>
                    </div>
                    
                    <!-- 显示名称 -->
                    <div>
                        <label for="display_name" class="block text-sm font-medium text-gray-700 mb-2">
                            显示名称 <span class="text-red-500">*</span>
                        </label>
                        <input type="text" 
                               id="display_name" 
                               x-model="formData.display_name" 
                               placeholder="请输入显示名称（中文，如：管理员）" 
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                               :class="errors.display_name ? 'border-red-500' : ''">
                        <p x-show="errors.display_name" class="mt-1 text-sm text-red-600" x-text="errors.display_name"></p>
                    </div>
                </div>
                
                <!-- 描述 -->
                <div>
                    <label for="description" class="block text-sm font-medium text-gray-700 mb-2">
                        角色描述
                    </label>
                    <textarea id="description" 
                              x-model="formData.description" 
                              rows="3" 
                              placeholder="请输入角色描述" 
                              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"></textarea>
                </div>
                
                <!-- 状态 -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        角色状态
                    </label>
                    <div class="flex items-center space-x-6">
                        <label class="flex items-center">
                            <input type="radio" 
                                   x-model="formData.status" 
                                   value="active" 
                                   class="text-blue-600 focus:ring-blue-500">
                            <span class="ml-2 text-sm text-gray-700">启用</span>
                        </label>
                        <label class="flex items-center">
                            <input type="radio" 
                                   x-model="formData.status" 
                                   value="inactive" 
                                   class="text-blue-600 focus:ring-blue-500">
                            <span class="ml-2 text-sm text-gray-700">停用</span>
                        </label>
                    </div>
                </div>
                
                <!-- 权限分配 -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-4">
                        权限分配
                    </label>
                    
                    <div class="space-y-4 max-h-96 overflow-y-auto border border-gray-200 rounded-lg p-4">
                        <template x-for="group in permissionGroups" :key="group.name">
                            <div class="border border-gray-200 rounded-lg p-4">
                                <div class="flex items-center justify-between mb-3">
                                    <h4 class="text-md font-medium text-gray-900" x-text="group.display_name"></h4>
                                    <button type="button" 
                                            @click="toggleGroupPermissions(group)" 
                                            class="text-sm text-blue-600 hover:text-blue-800">
                                        <span x-text="isGroupSelected(group) ? '取消全选' : '全选'"></span>
                                    </button>
                                </div>
                                
                                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2">
                                    <template x-for="permission in group.permissions" :key="permission.id">
                                        <label class="flex items-center p-2 hover:bg-gray-50 rounded cursor-pointer">
                                            <input type="checkbox" 
                                                   :value="permission.id" 
                                                   x-model="formData.permission_ids" 
                                                   class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                                            <div class="ml-3">
                                                <div class="text-sm font-medium text-gray-900" x-text="permission.display_name"></div>
                                                <div class="text-xs text-gray-500" x-text="permission.name"></div>
                                            </div>
                                        </label>
                                    </template>
                                </div>
                            </div>
                        </template>
                    </div>
                    
                    <div class="mt-2 text-sm text-gray-500">
                        已选择 <span class="font-medium text-blue-600" x-text="formData.permission_ids.length"></span> 个权限
                    </div>
                </div>
            </div>
            
            <!-- 操作按钮 -->
            <div class="mt-8 flex items-center justify-end space-x-4">
                <a href="/system/roles" class="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">
                    取消
                </a>
                <button type="submit" 
                        :disabled="loading" 
                        class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 flex items-center">
                    <span x-show="loading" class="mr-2">
                        <i class="fas fa-spinner fa-spin"></i>
                    </span>
                    <span x-text="loading ? '创建中...' : '创建角色'"></span>
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function roleCreate() {
    return {
        // 表单数据
        formData: {
            name: '',
            display_name: '',
            description: '',
            status: 'active',
            permission_ids: []
        },
        
        // 错误信息
        errors: {},
        
        // 加载状态
        loading: false,
        
        // 权限数据
        permissions: [],
        permissionGroups: [],
        initialized: false,
        
        // 初始化
        async init() {
            // 防止重复初始化
            if (this.initialized) {
                return;
            }
            this.initialized = true;
            
            await this.loadPermissions();
        },
        
        // 加载权限列表
        async loadPermissions() {
            try {
                const response = await fetch('/api/v1/system/permissions');
                const result = await response.json();
                
                if (result.code === 200) {
                    this.permissions = result.data.permissions || [];
                    this.groupPermissions();
                } else {
                    console.error('权限API返回错误:', result);
                    this.showToast('加载权限列表失败: ' + (result.message || '未知错误'), 'error');
                }
            } catch (error) {
                console.error('加载权限列表失败:', error);
                this.showToast('加载权限列表失败', 'error');
            }
        },
        
        // 权限分组
        groupPermissions() {
            const groups = {};
            this.permissions.forEach(permission => {
                const groupName = permission.name.split('.')[0];
                if (!groups[groupName]) {
                    groups[groupName] = {
                        name: groupName,
                        display_name: this.getGroupDisplayName(groupName),
                        permissions: []
                    };
                }
                groups[groupName].permissions.push(permission);
            });
            this.permissionGroups = Object.values(groups);
        },
        
        // 获取权限组显示名称
        getGroupDisplayName(groupName) {
            const groupNames = {
                'user': '用户管理',
                'role': '角色管理',
                'permission': '权限管理',
                'customer': '客户管理',
                'partner': '合作伙伴',
                'push': '推送管理',
                'system': '系统管理'
            };
            return groupNames[groupName] || groupName;
        },
        
        // 验证角色名称
        async validateName() {
            if (!this.formData.name) {
                this.errors.name = '角色名称不能为空';
                return;
            }
            
            if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(this.formData.name)) {
                this.errors.name = '角色名称只能包含字母、数字和下划线，且必须以字母开头';
                return;
            }
            
            // 检查角色名称是否已存在
            try {
                const response = await fetch(`/api/v1/system/roles/check-name?name=${encodeURIComponent(this.formData.name)}`);
                const result = await response.json();
                
                if (result.data.exists) {
                    this.errors.name = '角色名称已存在';
                } else {
                    this.errors.name = '';
                }
            } catch (error) {
                console.error('检查角色名称失败:', error);
            }
        },
        
        // 切换权限组选择
        toggleGroupPermissions(group) {
            const groupPermissionIds = group.permissions.map(p => p.id);
            const isSelected = this.isGroupSelected(group);
            
            if (isSelected) {
                // 取消选择该组的所有权限
                this.formData.permission_ids = this.formData.permission_ids.filter(id => !groupPermissionIds.includes(id));
            } else {
                // 选择该组的所有权限
                const newIds = groupPermissionIds.filter(id => !this.formData.permission_ids.includes(id));
                this.formData.permission_ids = [...this.formData.permission_ids, ...newIds];
            }
        },
        
        // 检查权限组是否全选
        isGroupSelected(group) {
            const groupPermissionIds = group.permissions.map(p => p.id);
            return groupPermissionIds.every(id => this.formData.permission_ids.includes(id));
        },
        
        // 验证表单
        validateForm() {
            this.errors = {};
            
            if (!this.formData.name) {
                this.errors.name = '角色名称不能为空';
            } else if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(this.formData.name)) {
                this.errors.name = '角色名称只能包含字母、数字和下划线，且必须以字母开头';
            }
            
            if (!this.formData.display_name) {
                this.errors.display_name = '显示名称不能为空';
            }
            
            return Object.keys(this.errors).length === 0;
        },
        
        // 提交表单
        async submitForm() {
            if (!this.validateForm()) {
                this.showToast('请检查表单输入', 'error');
                return;
            }
            
            this.loading = true;
            
            try {
                const response = await fetch('/api/v1/system/roles', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(this.formData)
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    this.showToast('角色创建成功', 'success');
                    setTimeout(() => {
                        window.location.href = '/system/roles';
                    }, 1500);
                } else {
                    this.showToast(result.message || '创建失败', 'error');
                }
            } catch (error) {
                console.error('创建角色失败:', error);
                this.showToast('创建角色失败', 'error');
            } finally {
                this.loading = false;
            }
        },
        
        // 显示提示信息
        showToast(message, type = 'info') {
            // 这里可以集成一个 toast 组件
            console.log(`${type}: ${message}`);
            alert(message);
        }
    };
}
</script>
{{end}}